<template>
  <div class="WebSocketDemo">
       {{msgFromServer}}<br /> 
       <input v-model="dataToSending" placeholder="设备ID"  /> 
       <button  v-on:click='onSendClick'>发送</button>

  </div>
</template>

<script>
  import {EventBus} from '@/eventbus/event-bus.js'

  export default {
    name : 'WebSocketDemo',

    data() {
      return {
        websock: null,
        msgFromServer:'来自服务器的消息',
        dataToSending:'待发送的消息' ,
      }
    },
    created() {
      this.initWebSocket();
    },

    destroyed() {
      this.websock.close() //离开路由之后断开websocket连接
    },
    methods: {
      initWebSocket(){ //初始化weosocket
        const wsuri = "ws://127.0.0.1:8080/websocket";
        this.websock = new WebSocket(wsuri);
        this.websock.onmessage = this.websocketonmessage;
        this.websock.onopen = this.websocketonopen;
        this.websock.onerror = this.websocketonerror;
        this.websock.onclose = this.websocketclose;
      },
      websocketonopen(){ //连接建立之后执行send方法发送数据
        let actions = {"test":"12345"};
        this.websocketsend(JSON.stringify(actions));
        console.log('connected to websocket server ')
      },
      websocketonerror(e){//连接建立失败重连
         //console.log(e)
        this.initWebSocket();
      },
      websocketonmessage(e){ //数据接收
          //{"equipmentId":123,"level":3 }
          const  retJson = JSON.parse(e.data);
         console.log( retJson );
          
         this.msgFromServer = retJson
         
        //业务判断，如果是告警，则用bus通知地图组件
        if (retJson.equipmentId) {
            EventBus.$emit('onalarm', {
                equipmentId: retJson.equipmentId
            })
        }
         
      },
      websocketsend(Data){//数据发送
        this.websock.send(Data);
      },
      onSendClick (){
          this.websocketsend(this.dataToSending)
      },
      websocketclose(e){  //关闭
        console.log('websocket  disconnetced',e);
      },
    },
  }
</script>

<style  >
 
</style>